package com.yangwp.doutu.service.impl;

import com.yangwp.doutu.service.HtmlService;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

@Service
public class HtmlServiceImpl implements HtmlService {

    @Override
    public String getBody(String url){
        CloseableHttpResponse resp = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            resp = closeableHttpClient.execute(httpGet);
            HttpEntity respEntity = resp.getEntity();
            String body = EntityUtils.toString(respEntity, Charsets.UTF_8);
            return body;
        } catch (Exception e) {
            System.out.println("request error:" + url);
        }finally {
            try {
                if(resp != null){
                    resp.close();
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

}
